package com.sgcc.nfc.lock.presentation.home

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.sgcc.nfc.lock.databinding.ItemWarningBinding
import com.sgcc.nfc.lock.domain.model.Warning

class WarningAdapter(
    private val onItemClick: (Warning) -> Unit
) : ListAdapter<Warning, WarningAdapter.WarningViewHolder>(DiffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WarningViewHolder {
        val binding = ItemWarningBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return WarningViewHolder(binding)
    }

    override fun onBindViewHolder(holder: WarningViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class WarningViewHolder(
        private val binding: ItemWarningBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Warning) {
            binding.warningType.text = item.warningContent ?: item.warningType.name
            binding.warningRoom.text = item.roomName ?: "--"
            binding.warningTime.text = item.createTime ?: "--"
            binding.root.setOnClickListener { onItemClick(item) }
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<Warning>() {
        override fun areItemsTheSame(oldItem: Warning, newItem: Warning): Boolean = oldItem.warningId == newItem.warningId
        override fun areContentsTheSame(oldItem: Warning, newItem: Warning): Boolean = oldItem == newItem
    }
}
